package com.ruoyi.websocket.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.websocket.utils.WebSocketSessionUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class ChatRoomSessionIdWebsocketHandler extends TextWebSocketHandler {

    /* todo 实现的功能清单
    * 1、连接websocket后显示当前用户连接信息
    * 2、查看当前所有在线的人，并计算出数量
    * 3、实现群聊（广播）
    * 4、实现私聊（单播）
    * 5、实现用户退出时，发送断开连接信息
    * 6、实现重连机制
    * 7、实现心跳检测
    * 8、显示消息状态，比如是否已读、已送达
    * */

    Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @Override
    // 连接建立时触发
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //连接成功后，加入集合
        WebSocketSessionUtil.addSession(session);
        System.out.println("连接建立成功："+session.getId());
        System.out.println("当前在线人数："+WebSocketSessionUtil.getOnlineCount());
        WebSocketSessionUtil.getAllSessions().forEach(s -> {
            System.out.println("在线SessionID："+s.getId());
        });
        broadcastMessage("【广播信息】"+"["+session.getId()+"]"+"-连接成功");
        // 推送最新用户列表
        broadcastUserList();
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 断开连接时移除
        WebSocketSessionUtil.removeSession(session);
        System.out.println("连接关闭：" + session.getId());
        System.out.println("当前在线人数："+WebSocketSessionUtil.getOnlineCount());
        WebSocketSessionUtil.getAllSessions().forEach(s -> {
            System.out.println("在线SessionID："+s.getId());
        });
        broadcastMessage("【广播信息】"+"["+session.getId()+"]"+"-退出连接");
        // 推送最新用户列表
        broadcastUserList();
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        JSONObject json = JSON.parseObject(message.getPayload());
        String type = json.getString("type");
        String content = json.getString("content");
        String fromUserId = session.getId();

        System.out.println(session.getId() + " 发送消息：" + content);

        if ("broadcast".equals(type)) {
            // 广播给所有在线用户
            for (WebSocketSession s : WebSocketSessionUtil.getAllSessions()) {
                if (s.isOpen()) {
                    s.sendMessage(new TextMessage("[群聊] " + fromUserId + "：" + content));
                }
            }
        } else if ("private".equals(type)) {
            String toUserId = json.getString("toUserId");
            WebSocketSession toSession = WebSocketSessionUtil.getSession(toUserId);
            if (toSession != null && toSession.isOpen()) {
                toSession.sendMessage(new TextMessage("[私聊] " + fromUserId + "：" + content));
            } else {
                session.sendMessage(new TextMessage("用户 " + toUserId + " 不在线"));
            }
        }
    }

    private void broadcastUserList() {
        List<String> onlineUsers = WebSocketSessionUtil.getAllSessions().stream()
                .map(WebSocketSession::getId) // 你可以替换成用户ID（如 session.getAttributes().get("userId")）
                .collect(Collectors.toList());

        JSONObject json = new JSONObject();
        json.put("type", "userList");
        json.put("users", onlineUsers);

        TextMessage userListMessage = new TextMessage(json.toJSONString());

        for (WebSocketSession s : WebSocketSessionUtil.getAllSessions()) {
            if (s.isOpen()) {
                try {
                    s.sendMessage(userListMessage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void broadcastMessage(String message) {
        for (WebSocketSession s : WebSocketSessionUtil.getAllSessions()) {
            if (s.isOpen()) {
                try {
                    s.sendMessage(new TextMessage(message));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }






}
